package com.atguigu.guli.service.edu.service.impl;

import com.atguigu.guli.service.base.dto.CourseDto;
import com.atguigu.guli.service.edu.entity.*;
import com.atguigu.guli.service.edu.entity.form.CourseInfoForm;
import com.atguigu.guli.service.edu.entity.vo.*;
import com.atguigu.guli.service.edu.feign.OssFileSerrvice;
import com.atguigu.guli.service.edu.mapper.*;
import com.atguigu.guli.service.edu.service.CourseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wangyang
 * @since 2021-05-26
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    private OssFileSerrvice ossFileSerrvice;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CourseCollectMapper courseCollectMapper;

    @Autowired
    private VideoMapper videoMapper;





    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {
        //首先保存课程信息
        Course course = new Course();
        course.setStatus(Course.COURSE_DRAFT);
        BeanUtils.copyProperties(courseInfoForm,course);
        baseMapper.insert(course);

        //保存课程详情
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.insert(courseDescription);
        return course.getId();
    }

    @Override
    public CourseInfoForm getCourseById(String id) {
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        Course course = baseMapper.selectById(id);
        if (course == null)  {
            return null;
        }
        BeanUtils.copyProperties(course,courseInfoForm);

        CourseDescription courseDescription = courseDescriptionMapper.selectById(id);
        courseInfoForm.setDescription(courseDescription.getDescription());
        return courseInfoForm;
    }

    @Override
    public void updateCourseInfoById(CourseInfoForm courseInfoForm) {
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm,course);
        baseMapper.updateById(course);

        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseDescription.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.updateById(courseDescription);
    }

    @Override
    public IPage<CourseVo> selectPage(long currentPage, long pageSize, CourseQueryVo courseQueryVo) {

        Page<CourseVo> page = new Page<>(currentPage, pageSize);

        QueryWrapper<CourseVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("c.gmt_create");

        /* 这里不能使用这个方法查询，因为查询的结果实体类字段与数据库不匹配，
           这里需要跨多表查询
        if (courseQueryVo == null) {
            return baseMapper.selectPage(page,queryWrapper);
        }*/

        String title = courseQueryVo.getTitle();
        String subjectParentId = courseQueryVo.getSubjectParentId();
        String subjectId = courseQueryVo.getSubjectId();
        String teacherId = courseQueryVo.getTeacherId();

        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like("c.title",title);
        }
        if (StringUtils.isNotBlank(subjectParentId)) {
            queryWrapper.eq("c.subject_parent_id",subjectParentId);
        }
        if (StringUtils.isNotBlank(subjectId)) {
            queryWrapper.eq("c.subject_id",subjectId);
        }
        if (StringUtils.isNotBlank(teacherId)) {
            queryWrapper.eq("c.teacher_id",teacherId);
        }

        List<CourseVo> result = baseMapper.selectPageByCourseQueryVo(page,queryWrapper);
        page.setRecords(result);
        return page;
    }

    @Override
    public void removeCoverById(String id) {
        Course course = baseMapper.selectById(id);
        if(course != null) {
            String cover = course.getCover();
            if (StringUtils.isNotBlank(cover)) {
                ossFileSerrvice.removeFile(cover);
            }
        }
    }

    @Override
    public boolean removeCourseById(String id) {
        //删除章节信息
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",id);
        chapterMapper.delete(chapterQueryWrapper);

        //删除评论
        QueryWrapper<Comment> commentMapperQueryWrapper = new QueryWrapper<>();
        commentMapperQueryWrapper.eq("course_id",id);
        commentMapper.delete(commentMapperQueryWrapper);

        //删除收藏信息
        QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
        courseCollectQueryWrapper.eq("course_id",id);
        courseCollectMapper.delete(courseCollectQueryWrapper);

        //删除描述信息
        courseDescriptionMapper.selectById(id);

        //删除课程
        return this.removeById(id);
    }

    @Override
    public CoursePublishVo getPublishCourseById(String id) {
        return baseMapper.getPublishCourseById(id);
    }

    @Override
    public boolean publishCourseById(String id) {
        Course course = new Course();
        course.setStatus(Course.COURSE_NORMAL);
        course.setId(id);
        return this.updateById(course);
    }

    @Override
    public List<Course> findByCondition(WebCourseQueryVo webCourseQueryVo) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        //查询发布的课程，因为只有发布的课程才展示
        queryWrapper.eq("status",Course.COURSE_NORMAL);
        if (StringUtils.isNotBlank(webCourseQueryVo.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", webCourseQueryVo.getSubjectParentId());
        }

        if (StringUtils.isNotBlank(webCourseQueryVo.getSubjectId())) {
            queryWrapper.eq("subject_id", webCourseQueryVo.getSubjectId());
        }

        if (StringUtils.isNotBlank(webCourseQueryVo.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (StringUtils.isNotBlank(webCourseQueryVo.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (StringUtils.isNotBlank(webCourseQueryVo.getPriceSort())) {
            if (webCourseQueryVo.getType() == null || webCourseQueryVo.getType() == 1) {
                queryWrapper.orderByAsc("price");
            } else {
                queryWrapper.orderByDesc("price");
            }
        }
        List<Course> courseList = baseMapper.selectList(queryWrapper);
        return courseList;
    }

    @Override
    public WebCourseVo findTeacherAndCourse(String courseId) {
        //更新课程浏览数
        Course course = baseMapper.selectById(courseId);
        course.setViewCount(course.getViewCount()+1);
        baseMapper.updateById(course);

        //查询
        return baseMapper.findTeacherAndCourse(courseId);
    }

    @Cacheable(value = "index", key = "'selectHotCourse'")
    @Override
    public List<Course> selectHotCourse() {
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.orderByDesc("view_count");
        courseQueryWrapper.last("limit 8");  //last为拼接到SQL语句最后
        return baseMapper.selectList(courseQueryWrapper);
    }

    @Override
    public CourseDto getCourseDtoById(String courseId) {

        return baseMapper.getCourseDtoById(courseId);
    }
}
